package main

import (
	"time"

	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/client-go/informers"
)

var sharedInformerFactory informers.SharedInformerFactory
var stopCh chan struct{}
var clients Clients

func NewShareInformerFactory() (err error) {

	// 加载客户端
	clients = NewClients()

	// 实例化informer
	sharedInformerFactory = informers.NewSharedInformerFactory(clients.ClientSet(), time.Second*60)

	// 启动(只需配置自已需要启动的即可)
	gvrs := []schema.GroupVersionResource{
		{Group: "", Version: "v1", Resource: "pods"},
		{Group: "", Version: "v1", Resource: "services"},
		{Group: "", Version: "v1", Resource: "namespaces"},
		{Group: "apps", Version: "v1", Resource: "deployments"},
		{Group: "apps", Version: "v1", Resource: "statefulsets"},
		{Group: "apps", Version: "v1", Resource: "daemonsets"},
	}

	for _, v := range gvrs {
		_, err = sharedInformerFactory.ForResource(v) // 创建了informer, 但还没有启动
		if err != nil {
			return
		}
	}

	// 等待所有informer启动并全量同步完成
	sharedInformerFactory.Start(stopCh)
	sharedInformerFactory.WaitForCacheSync(stopCh)

	return
}

func Get() informers.SharedInformerFactory {
	return sharedInformerFactory
}

func GetClients() Clients {
	return clients
}

func Setup() (err error) {
	stopCh = make(chan struct{})
	err = NewShareInformerFactory()
	if err != nil {
		return
	}
	return
}
